<template>
  <!-- 多文件上传 -->
  <el-dialog v-model="model" width="500">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="action"
      :headers="headers"
      drag
      :limit="props.limit"
      :on-exceed="handleExceed"
      :auto-upload="false"
      :on-change="handleChange"
      :on-success="handleSuccess"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        {{ $t("common.dragFiles") }}<em>{{ $t("common.uploadEvent") }}</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          注：可上传pdf/word/excel/ppt/txt/图片/压缩包
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitUpload">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref } from "vue";
import {
  type UploadInstance,
  type UploadProps,
  type UploadUserFile,
  type UploadRawFile,
  ElMessageBox,
  genFileId,
} from "element-plus";
import { fileApi } from "@/api/file";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
// 上传文件的地址
const action = ref(fileApi.uploadUrl());
// 请求上传的头部
const headers = ref(fileApi.authHeader());
const uploadRef = ref<UploadInstance>();
const model = defineModel<boolean>();
const fileList = ref<UploadUserFile[]>([]);
// 传参
const props = defineProps({
  limit: {
    type: Number,
    default: 1,
  },
});
console.log(props);
const emits = defineEmits(["filesResponse", "uploadFileList"]);
const handleChange: UploadProps["onChange"] = async (uploadFile) => {
  console.log(uploadFile);
  if (!uploadFile) return;
  if (uploadFile.status !== "ready") return;
  // 图片最大限制
  const isLt2M = (uploadFile!.size as number) / 1024 / 1024 < 2;
  // 文件最大限制
  const isLt10M = (uploadFile!.size as number) / 1024 / 1024 < 10;
  const imageTypes = ["image/jpeg", "image/png", "image/gif", "image/jpg"];
  const isImageTypes = imageTypes.includes(uploadFile!.raw!.type);
  if (isImageTypes && !isLt2M) {
    return handleFileOverSize(uploadFile, t("file.imageLtRequired"));
  } else if (!isLt10M) {
    return handleFileOverSize(uploadFile, t("file.fileLtRequired"));
  }
};

// 文件上传成功
const handleSuccess: UploadProps["onSuccess"] = (files, uploadFiles) => {
  console.log(files, uploadFiles);
  if (files.fileId) {
    ElMessage({
      message: t("common.submitSuccess"),
      type: "success",
    });
    if (model.value) {
      model.value = false;
    }
  }
  emits("filesResponse", files);
  emits("uploadFileList", uploadFiles);
};

const handleExceed: UploadProps["onExceed"] = (files) => {
  console.log("....", files);
  uploadRef.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
};

// 手动上传文件
function submitUpload() {
  uploadRef.value!.submit();
}

// 清空文件列表
const clearFileList = () => {
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
};

// 抛出uploadRef
defineExpose({ clearFileList });

// 封装判断文件超出大小
const handleFileOverSize = async (
  uploadFile: any,
  message: string,
): Promise<boolean> => {
  console.log(uploadFile, message);
  return new Promise((resolve) => {
    ElMessageBox.confirm(message, t("file.warning"), {
      confirmButtonText: t("common.confirm"),
      cancelButtonText: t("common.cancel"),
      type: "warning",
    })
      .then(() => {
        resolve(true);
      })
      .catch(() => {
        console.log(fileList.value);
        const index = fileList.value.findIndex(
          (file) => file.name === uploadFile.name,
        );
        console.log(index);
        if (index !== -1) {
          fileList.value.splice(index, 1); // 从fileList中移除匹配的文件
        }
        resolve(false); // 用户取消操作，将Promise对象解决为false
      });
  });
};
</script>
